package gen

import (
	"bufio"
	"fmt"
	"game/game-design-v.xnanz/export"
	"log"
	"os"
	"strings"
)

type GenArgs struct {
	TemplateFile string
	SourceHome   string
	Args         map[string]string
	Reader       export.IDesignIO
}

func NewGenArgs(args []string) *GenArgs {
	var genArgs GenArgs
	genArgs.Args = make(map[string]string)

	for _, arg := range args {
		parts := strings.Split(arg, " ")

		if strings.HasPrefix(arg, "-template") {

			genArgs.TemplateFile = parts[1]

		} else if strings.HasPrefix(arg, "-sourcehome") {
			genArgs.SourceHome = parts[1]

		} else if strings.HasPrefix(arg, "-reader") {
			genArgs.Reader = export.GetDesignIO(parts[1])

		} else if strings.HasPrefix(arg, "-arg") {
			genArgs.Args[parts[1]] = parts[2]

			//TODO 这里好恶心
			Params[parts[1]] = parts[2]

		}
		// else if strings.HasPrefix(arg, "-genfor") {
		// 	tagParts := strings.Split(parts[1], ",")
		// 	for _, v := range tagParts {
		// 		var taging []string
		// 		parts := strings.Split(v, "&")
		// 		taging = append(taging, parts...)
		// 		genArgs.GenFor = append(genArgs.GenFor, taging)
		// 	}
		// }
	}
	return &genArgs
}

func (g *GenArgs) Check() bool {
	fullfill := true
	if g.TemplateFile == "" {
		fmt.Println("未指定模板文件")
		fullfill = false
	}
	if g.SourceHome == "" {
		fmt.Println("未指定配置源文件")
		fullfill = false
	}
	if g.Reader == nil {
		fmt.Println("未指定配置文件解释方式")
		fullfill = false
	}
	return fullfill
}

func ReadTemplateFile(templateFile string) []string {
	file, err := os.Open(templateFile)
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()
	//读取代码模板
	lines := []string{}
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}
	if err := scanner.Err(); err != nil {
		log.Fatal(err)
	}
	return lines
}
